<template>
  <div class="product-attribute-page">
    <el-card class="attribute-card">
      <template #header>
        <div class="card-header">
          <span>商品属性管理</span>
          <div style="display: flex; align-items: center; gap: 12px;">
            <el-input v-model="searchAttrName" placeholder="请输入属性名称" clearable style="width: 200px;" @keyup.enter="handleSearch" />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="primary" @click="handleAdd" v-if="hasPerm('product:attribute:add')">
              <el-icon><Plus/></el-icon>
              新增属性
            </el-button>
          </div>
        </div>
      </template>
      <el-table :data="attributeList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="attrName" label="属性名称" width="200" />
        <el-table-column prop="attrValues" label="属性值" min-width="300">
          <template #default="scope">
            <el-tag
                v-for="value in scope.row.attrValues"
                :key="value.id"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px;"
            >
              {{ value.attrValue }}
            </el-tag>
            <span v-if="!scope.row.attrValues || scope.row.attrValues.length === 0" style="color: #909399;">
              暂无属性值
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)" v-if="hasPerm('product:attribute:view')">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)" v-if="hasPerm('product:attribute:edit')">编辑</el-button>
            <el-button size="small" type="warning" @click="handleManageValues(scope.row)" v-if="hasPerm('product:attribute:edit')">管理属性值</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-if="hasPerm('product:attribute:delete')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 16px; text-align: right;">
        <el-pagination
            background
            layout="total, prev, pager, next, sizes"
            :total="total"
            :page-size="pageSize"
            :current-page="pageNum"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
            :page-sizes="[10, 20, 50, 100]"
        />
      </div>
    </el-card>

    <el-dialog
        v-model="attributeDialogVisible"
        :title="attributeDialogTitle"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="attributeFormRef"
          :model="attributeForm"
          :rules="attributeRules"
          label-width="100px"
      >
        <el-form-item label="属性名称" prop="attrName">
          <el-input v-model="attributeForm.attrName" placeholder="请输入属性名称，如：颜色、尺码"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="attributeForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="attributeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAttributeForm" :loading="attributeSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="viewDialogVisible"
        title="属性详情"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="属性名称">{{ viewData.attrName }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.status === 1 ? 'success' : 'danger'">
            {{ viewData.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="属性值">
          <template v-if="viewData.attrValues && viewData.attrValues.length">
            <el-tag
                v-for="v in viewData.attrValues"
                :key="v.id"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px;"
            >{{ v.attrValue }}</el-tag>
          </template>
          <span v-else style="color: #909399;">暂无属性值</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 属性值管理对话框 -->
    <el-dialog
      v-model="valueDialogVisible"
      :title="`管理属性值 - ${currentAttribute?.attrName || ''}`"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="value-management">
        <div class="value-header">
          <el-button type="primary" size="small" @click="handleAddValue">
            <el-icon><Plus/></el-icon>
            新增属性值
          </el-button>
        </div>
        
        <el-table :data="attributeValueList" style="width: 100%" v-loading="valueLoading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="attrValue" label="属性值" min-width="200" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                {{ scope.row.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEditValue(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDeleteValue(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 属性值表单对话框 -->
      <el-dialog
        v-model="valueFormDialogVisible"
        :title="valueFormDialogTitle"
        width="500px"
        :close-on-click-modal="false"
        append-to-body
      >
        <el-form
          ref="valueFormRef"
          :model="valueForm"
          :rules="valueRules"
          label-width="100px"
        >
          <el-form-item label="属性值" prop="attrValue">
            <el-input v-model="valueForm.attrValue" placeholder="请输入属性值，如：红色、L码"/>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="valueForm.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="valueFormDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitValueForm" :loading="valueSubmitting">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { hasPerm } from '@/utils/permission'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getAttributeList,
  getAttributeDetail,
  addAttribute,
  updateAttribute,
  deleteAttribute,
  getAttributeValueList,
  addAttributeValue,
  updateAttributeValue,
  deleteAttributeValue
} from '@/api/product'
// 搜索与分页相关数据
const searchAttrName = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 响应式数据
const loading = ref(false)
const attributeList = ref([])
const attributeDialogVisible = ref(false)
const attributeDialogTitle = ref('新增属性')
const attributeSubmitting = ref(false)
const attributeFormRef = ref(null)
const viewDialogVisible = ref(false)
const viewData = ref({
  attrName: '',
  status: 1,
  attrValues: []
})
// 属性表单
const attributeForm = ref({
  id: null,
  attrName: '',
  status: 1
})

// 属性表单验证规则
const attributeRules = {
  attrName: [
    { required: true, message: '请输入属性名称', trigger: 'blur' },
    { min: 2, max: 20, message: '属性名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 属性值管理相关
const valueDialogVisible = ref(false)
const valueLoading = ref(false)
const attributeValueList = ref([])
const currentAttribute = ref(null)
const valueFormDialogVisible = ref(false)
const valueFormDialogTitle = ref('新增属性值')
const valueSubmitting = ref(false)
const valueFormRef = ref(null)

// 属性值表单
const valueForm = ref({
  id: null,
  attrId: null,
  attrValue: '',
  status: 1
})

// 属性值表单验证规则
const valueRules = {
  attrValue: [
    { required: true, message: '请输入属性值', trigger: 'blur' },
    { min: 1, max: 50, message: '属性值长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}
// 获取属性列表（支持分页和搜索）
const loadAttributeList = async() => {
  try {
    loading.value = true
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      attrName: searchAttrName.value
    }
    const response = await getAttributeList(params)
    if (response && response.code === 200) {
      attributeList.value = response.data?.list || []
      total.value = response.data?.total || 0
    } else {
      attributeList.value = []
      total.value = 0
    }
  } catch (error) {
    attributeList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}
const handleSearch = () => {
  pageNum.value = 1
  loadAttributeList()
}
const handlePageChange = (val) => {
  pageNum.value = val
  loadAttributeList()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1
  loadAttributeList()
}
// 获取属性值列表
const loadAttributeValueList = async(attrId) => {
  try {
    valueLoading.value = true
    const response = await getAttributeValueList(attrId)
    console.log('属性值列表响应:', response)
    
    if (response && response.code === 200) {
      attributeValueList.value = response.data || []
    } else {
      console.error('属性值列表响应格式错误:', response)
      attributeValueList.value = []
    }
  } catch (error) {
    console.error('获取属性值列表失败:', error)
    ElMessage.error('获取属性值列表失败')
    attributeValueList.value = []
  } finally {
    valueLoading.value = false
  }
}

// 属性操作
const handleAdd = () => {
  attributeForm.value = {
    id: null,
    attrName: '',
    status: 1
  }
  attributeDialogTitle.value = '新增属性'
  attributeDialogVisible.value = true
}

const handleView = async(row) => {
  try {
    const response = await getAttributeDetail(row.id)
    if (response && response.code === 200) {
      viewData.value = response.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error('获取属性详情失败')
    }
  } catch (error) {
    console.error('获取属性详情失败:', error)
    ElMessage.error('获取属性详情失败')
  }
}

const handleEdit = async(row) => {
  try {
    const response = await getAttributeDetail(row.id)
    if (response && response.code === 200) {
      attributeForm.value = { ...response.data }
      attributeDialogTitle.value = '编辑属性'
      attributeDialogVisible.value = true
    } else {
      ElMessage.error('获取属性详情失败')
    }
  } catch (error) {
    console.error('获取属性详情失败:', error)
    ElMessage.error('获取属性详情失败')
  }
}

const handleDelete = async(row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除属性"${row.attrName}"吗？删除后该属性下的所有属性值也将被删除。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAttribute(row.id)
    ElMessage.success('删除成功')
    loadAttributeList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const submitAttributeForm = async() => {
  try {
    await attributeFormRef.value.validate()
    attributeSubmitting.value = true
    
    if (attributeForm.value.id) {
      // 编辑
      await updateAttribute(attributeForm.value)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addAttribute(attributeForm.value)
      ElMessage.success('新增成功')
    }
    
    attributeDialogVisible.value = false
    loadAttributeList()
  } catch (error) {
    console.error('提交属性表单失败:', error)
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    attributeSubmitting.value = false
  }
}

// 属性值管理操作
const handleManageValues = async(row) => {
  currentAttribute.value = row
  valueDialogVisible.value = true
  await loadAttributeValueList(row.id)
}

const handleAddValue = () => {
  valueForm.value = {
    id: null,
    attrId: currentAttribute.value.id,
    attrValue: '',
    status: 1
  }
  valueFormDialogTitle.value = '新增属性值'
  valueFormDialogVisible.value = true
}

const handleEditValue = (row) => {
  valueForm.value = { ...row }
  valueFormDialogTitle.value = '编辑属性值'
  valueFormDialogVisible.value = true
}

const handleDeleteValue = async(row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除属性值"${row.attrValue}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAttributeValue(row.id)
    ElMessage.success('删除成功')
    loadAttributeValueList(currentAttribute.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const submitValueForm = async() => {
  try {
    await valueFormRef.value.validate()
    valueSubmitting.value = true
    
    if (valueForm.value.id) {
      // 编辑
      await updateAttributeValue(valueForm.value)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await addAttributeValue(valueForm.value)
      ElMessage.success('新增成功')
}

    valueFormDialogVisible.value = false
    loadAttributeValueList(currentAttribute.value.id)
  } catch (error) {
    console.error('提交属性值表单失败:', error)
    if (error !== false) {
      ElMessage.error('操作失败')
    }
  } finally {
    valueSubmitting.value = false
  }
}

// 初始化
onMounted(() => {
  loadAttributeList()
})
</script>

<style scoped>
.product-attribute-page {
  padding: 20px;
}

.attribute-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.value-management {
  padding: 20px 0;
}

.value-header {
  margin-bottom: 15px;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

/* 卡片样式 */
:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 标签样式 */
:deep(.el-tag) {
  margin-right: 5px;
  margin-bottom: 5px;
}
</style>